package aooO.crm.Controller;

import aooO.crm.Service.*;
import aooO.crm.common.Utils.DateUtils;
import aooO.crm.common.Utils.UUIDUtils;
import aooO.crm.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("workbench/contacts")
public class contactsController {

    @Autowired
    DicValueService dicValueService;

    @Autowired
    UserService userService;

    @Autowired
    ContactsService contactsService;

    @Autowired
    CustomerService customerService;

    @Autowired
    ActivityService activityService;

    @Autowired
    ContactsRemarkService contactsRemarkService;

    @Autowired
    ContactsActivityRelationService carMapper;

    //    workbench/contacts/index.do
    @RequestMapping("/index.do")
    public String index(HttpServletRequest request) {
        //分页查询所有的联系人
        List<User> userList = userService.selectAllUser();
        List<DicValue> sourceList = dicValueService.queryDicValueByTypeCode("source");
        List<DicValue> appellationList = dicValueService.queryDicValueByTypeCode("appellation");
        request.setAttribute("sourceList", sourceList);
        request.setAttribute("userList", userList);
        request.setAttribute("appellationList", appellationList);
        return "workbench/contacts/index";
    }

    //    'workbench/contacts/queryContactsByConditionForPage.do'
    @RequestMapping("/queryContactsByConditionForPage.do")
    @ResponseBody
    public Object queryContactsByConditionForPage(String owner, String fullname, String customerId, String source, String job, int pageNo, int pageSize) {
       /* owner:owner,
        fullname:fullname,
        customerId:customerId,
        source:source,
        job:job,
        pageNo:pageNo,
        pageSize:pageSize*/
        Map<String, Object> map = new HashMap<>();
        map.put("owner", owner);
        map.put("customerId", customerId);
        map.put("source", source);
        map.put("fullname", fullname);
        map.put("job", job);
        int beginNo = (pageNo - 1) * pageSize;
        map.put("beginNo", beginNo);
        map.put("pageSize", pageSize);

        Map<String, Object> data = new HashMap<>();
        List<Contacts> contactsList = contactsService.selectContactsByConditionForPage(map);
        int totalRows = contactsService.selectTotalPageOfContacts(map);
        data.put("contactsList", contactsList);
        data.put("totalRows", totalRows);
        return data;
    }

    //    'workbench/contacts/queryCustomerNameByFuzzyName.do'  键盘弹起查名字关联的客户信息  customerName:jquery
    @RequestMapping("/queryCustomerNameByFuzzyName.do")
    @ResponseBody
    public Object queryCustomerNameByFuzzyName(String customerName) {
        List<String> data = customerService.queryCustomerNameByFuzzyName(customerName);
        return data;
    }

//    'workbench/contacts/saveCreateContacts.do'

    @RequestMapping("/saveCreateContacts.do")
    @ResponseBody
    public Object saveCreateContacts(Contacts contacts, HttpSession session) {
        returnObject data = new returnObject(stateCode.STATE_FAILURE, "");
       /* owner:owner,
        source:source,
        fullname:fullname,
        appellation:appellation,
        job:job,
        mphone:mphone,
        email:email,
        customerId:customerId,
        description:description,
        contactSummary:contactSummary,
        nextContactTime:nextContactTime,
        address:address*/
        User user = (User) session.getAttribute(stateCode.SESSION_USER);
        // 封装参数
        contacts.setId(UUIDUtils.uuid());
        contacts.setCreateBy(user.getId());
        contacts.setCreateTime(DateUtils.FormatDateTime(new Date()));

        returnObject msg = new returnObject(stateCode.STATE_FAILURE,"");
        try
        {
            int i = contactsService.insertContact(contacts);
            if (i > 0) {
                data.setCode(stateCode.STATE_SUCCESS);
            } else {
                data.setMessage("保存失败，请重试！");
            }
        }catch(Exception e)

        {
            e.printStackTrace();
            data.setMessage("保存失败，请重试！");
        }

        return data;
}


//    'workbench/contacts/queryContactsById.do'
    @RequestMapping("/queryContactsById.do")
    @ResponseBody
    public Object queryContactsById(String id) {
        return contactsService.selectContactsById(id);
}

//    'workbench/contacts/saveEditContacts.do'
    @RequestMapping("/saveEditContacts.do")
    @ResponseBody
    public Object saveEditContacts(Contacts contacts, HttpSession session){
        User user = (User) session.getAttribute(stateCode.SESSION_USER);
        // 封装参数
        contacts.setEditBy(user.getId());
        contacts.setCreateBy(user.getId());
        contacts.setEditTime(DateUtils.FormatDateTime(new Date()));
        returnObject msg = new returnObject(stateCode.STATE_FAILURE,"");

        // 更新操作
        try {
            contactsService.UpdateContacts(contacts);
            msg.setCode(stateCode.STATE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            msg.setMessage("系统繁忙，请稍后重试...");
        }
        return msg;
    }


//    'workbench/contacts/deleteContacts.do'
     @RequestMapping("/deleteContacts.do")
     @ResponseBody
     public Object deleteContacts(String[] id) {
         returnObject returnObject = new returnObject();
         try {
             contactsService.deleteContactsByIds(id); // 通过联系人id数组删除所有对应的线索以及该线索的所有信息
             returnObject.setCode(stateCode.STATE_SUCCESS);
         } catch (Exception e) { // 发生了某些异常，捕获后返回信息
             e.printStackTrace();
             returnObject.setCode(stateCode.STATE_FAILURE);
             returnObject.setMessage("系统繁忙，请稍后重试...");
         }
         return returnObject;
     }

    @RequestMapping("/detailContacts.do")
    public String detailContacts(String id, HttpServletRequest request) {
        // 查询对应id的联系人详细信息
        Contacts contacts = contactsService.selectContactsDetailById(id);
        // 查询对应id的联系人所有备注
        List<ContactsRemark> contactsRemarkList = contactsRemarkService.selectContactsRemarkForDetailByContactsId(id);
        // 查询对应id的联系人所关联的市场活动
        List<Activity> activityList = activityService.selectActivityForDetailByContactsId(id);
        // 存到request域中
        request.setAttribute("contacts", contacts);
        request.setAttribute("contactsRemarkList", contactsRemarkList);
        request.setAttribute("activityList", activityList);
        return  "workbench/contacts/detail";
    }

    @RequestMapping("/queryActivityForDetailByNameAndContactsId.do")
    @ResponseBody
    public Object queryActivityForDetailByNameAndContactsId(String activityName, String contactsId) {
        // 封装参数
        Map<String, Object> map = new HashMap<>();
        map.put("activityName", activityName);
        map.put("contactsId", contactsId);
        List<Activity> activityList = activityService.queryActivityForDetailByNameAndContactsId(map);
        return activityList;
    }

    //保存关联关系
    @RequestMapping("/saveBound.do")
    @ResponseBody
    public Object saveBound(String[] activityId, String contactsId) {
        // 封装参数
        ContactsActivityRelation contactsActivityRelation = null;
        List<ContactsActivityRelation> contactsActivityRelationList = new ArrayList<>();
        for (String actId : activityId) {
            contactsActivityRelation = new ContactsActivityRelation();
            contactsActivityRelation.setActivityId(actId);
            contactsActivityRelation.setContactsId(contactsId);
            contactsActivityRelation.setId(UUIDUtils.uuid());
            contactsActivityRelationList.add(contactsActivityRelation);
        }
        returnObject returnObject = new returnObject();
        try {
            int res = carMapper.insertCARelation(contactsActivityRelationList);
            if (res > 0) {
                returnObject.setCode(stateCode.STATE_SUCCESS);
                // 保存成功后查询所有市场活动id对应的市场活动，用于动态响应到前台页面
                List<Activity> activityList = activityService.selectActivitiesByIds(activityId);
                returnObject.setReturnData(activityList);
            } else {
                returnObject.setCode(stateCode.STATE_FAILURE);
                returnObject.setMessage("系统繁忙，请稍后重试...");
            }
        } catch (Exception e) { // 发生了某些异常，捕获后返回信息
            e.printStackTrace();
            returnObject.setCode(stateCode.STATE_FAILURE);
            returnObject.setMessage("系统繁忙，请稍后重试...");
        }
        return returnObject;
    }

    @RequestMapping("/saveUnbound.do")
    @ResponseBody
    public Object saveUnbound(ContactsActivityRelation contactsActivityRelation) {
        returnObject returnObject = new returnObject();
        try {
            int res = carMapper.deleteContactsActivityRelationByContactsIdAndActivityId(contactsActivityRelation);
            if (res > 0) {
                returnObject.setCode(stateCode.STATE_SUCCESS);
            } else {
                returnObject.setCode(stateCode.STATE_FAILURE);
                returnObject.setMessage("系统繁忙，请稍后重试...");
            }
        } catch (Exception e) { // 发生了某些异常，捕获后返回信息
            e.printStackTrace();
            returnObject.setCode(stateCode.STATE_FAILURE);
            returnObject.setMessage("系统繁忙，请稍后重试...");
        }
        return returnObject;
    }
}
